import { defineStore } from "pinia";
import { ref, computed } from "vue";
import { authApi, userApi } from "@/api/services";
import type { User, UserProfile, UserPreferences } from "@/types/user";

export const useUserStore = defineStore(
  "user",
  () => {
    // 状态
    const user = ref<User | null>(null);
    const token = ref<string>("");
    const refreshToken = ref<string>("");
    const isLoading = ref(false);
    const lastLoginTime = ref<Date | null>(null);
    const loginAttempts = ref(0);
    const maxLoginAttempts = 5;
    const preferences = ref({
      theme: "auto" as "light" | "dark" | "auto",
      language: "zh-CN",
      fontSize: "medium" as "small" | "medium" | "large",
      soundEnabled: true,
      notificationEnabled: true,
      autoSave: true,
      chatBubbleStyle: "modern" as "classic" | "modern" | "minimal",
    });

    // 计算属性
    const isAuthenticated = computed(() => {
      return !!token.value && !!user.value;
    });

    const userProfile = computed(() => {
      if (!user.value) return null;
      return {
        id: user.value.id,
        username: user.value.username,
        email: user.value.email,
        nickname: user.value.nickname,
        avatar: user.value.avatar,
        bio: user.value.bio,
        gender: user.value.gender,
        birthday: user.value.birthday,
        location: user.value.location,
        createdAt: user.value.createdAt,
        updatedAt: user.value.updatedAt,
      } as UserProfile;
    });

    const hasPermission = computed(() => {
      return (permission: string) => {
        if (!user.value) return false;
        return user.value.permissions?.includes(permission) || false;
      };
    });

    const hasRole = computed(() => {
      return (role: string) => {
        if (!user.value) return false;
        return user.value.role === role;
      };
    });

    const isEmailVerified = computed(() => {
      return user.value?.emailVerified || false;
    });

    const isPhoneVerified = computed(() => {
      return user.value?.phoneVerified || false;
    });

    const canLogin = computed(() => {
      return loginAttempts.value < maxLoginAttempts;
    });

    // 方法
    const setUser = (userData: User) => {
      user.value = userData;
      // 同时保存到本地存储
      localStorage.setItem("user", JSON.stringify(userData));
    };

    const setTokens = (accessToken: string, refreshTokenValue: string) => {
      token.value = accessToken;
      refreshToken.value = refreshTokenValue;
      // 同时更新 localStorage
      localStorage.setItem("token", accessToken);
      localStorage.setItem("refreshToken", refreshTokenValue);
    };

    const clearTokens = () => {
      token.value = "";
      refreshToken.value = "";
      localStorage.removeItem("token");
      localStorage.removeItem("refreshToken");
      localStorage.removeItem("user");
    };

    const setLoading = (loading: boolean) => {
      isLoading.value = loading;
    };

    const resetLoginAttempts = () => {
      loginAttempts.value = 0;
    };

    const login = async (credentials: {
      email: string;
      password: string;
      rememberMe?: boolean;
    }) => {
      try {
        setLoading(true);

        if (!canLogin.value) {
          throw new Error("登录尝试次数过多，请稍后再试");
        }

        const response = await authApi.login(credentials);
        const {
          user: userData,
          token: accessToken,
          refreshToken: refreshTokenValue,
        } = response;

        setUser(userData);
        setTokens(accessToken, refreshTokenValue);

        lastLoginTime.value = new Date();
        resetLoginAttempts();

        // 登录成功后加载用户资料和偏好设置
        await Promise.all([
          fetchProfile().catch(() => {}),
          loadUserPreferences().catch(() => {}),
        ]);

        return response;
      } catch (error) {
        loginAttempts.value++;
        throw error;
      } finally {
        setLoading(false);
      }
    };

    const loadUserPreferences = async () => {
      try {
        if (!user.value?.id) return;

        const userPrefs = await userApi.getUserPreferences();
        if (userPrefs.data) {
          preferences.value = { ...preferences.value, ...userPrefs.data };
          localStorage.setItem(
            "preferences",
            JSON.stringify(preferences.value),
          );
        }
      } catch (error) {
        // 加载用户偏好设置失败
      }
    };

    const register = async (userData: {
      username: string;
      email: string;
      password: string;
      nickname?: string;
      inviteCode?: string;
    }) => {
      try {
        isLoading.value = true;
        const response = await authApi.register(userData);

        // 注册成功后自动登录
        if (response.data.autoLogin) {
          const {
            user: userInfo,
            token: accessToken,
            refreshToken: refreshTokenValue,
          } = response.data;
          setUser(userInfo);
          setTokens(accessToken, refreshTokenValue);
          lastLoginTime.value = new Date();
        }

        return response;
      } finally {
        isLoading.value = false;
      }
    };

    const logout = async () => {
      // 尝试调用登出API，失败时忽略错误
      if (token.value) {
        try {
          await authApi.logout();
        } catch {
          // 忽略登出请求失败
        }
      }

      // 清除本地状态
      user.value = null;
      clearTokens();
      lastLoginTime.value = null;
      loginAttempts.value = 0;
    };

    const refreshAccessToken = async () => {
      if (!refreshToken.value) {
        throw new Error("没有刷新令牌");
      }

      try {
        const response = await authApi.refreshToken(refreshToken.value);
        const { token: newToken, refreshToken: newRefreshToken } = response;

        setTokens(newToken, newRefreshToken);
        return response;
      } catch (error) {
        // 刷新失败，清除所有认证信息
        await logout();
        throw error;
      }
    };

    const profile = ref<UserProfile | null>(null);

    const fetchProfile = async () => {
      try {
        if (!user.value?.id) return;

        const profileData = await userApi.getProfile(user.value.id);
        profile.value = profileData;

        // 合并用户偏好设置
        if (profileData.preferences) {
          preferences.value = {
            ...preferences.value,
            ...profileData.preferences,
          };
        }

        return profileData;
      } catch (error) {
        console.error("获取用户资料失败:", error);
        throw error;
      }
    };

    const updateProfile = async (profileData: Partial<UserProfile>) => {
      if (!user.value?.id) throw new Error("用户未登录");

      const updatedProfile = await userApi.updateProfile(
        user.value.id,
        profileData,
      );
      profile.value = updatedProfile;

      // 用户资料更新成功
      return updatedProfile;
    };

    const updatePreferences = async (
      newPreferences: Partial<typeof preferences.value>,
    ) => {
      try {
        preferences.value = { ...preferences.value, ...newPreferences };

        // 保存到本地存储
        localStorage.setItem("preferences", JSON.stringify(preferences.value));

        // 如果用户已登录，同步到服务器
        if (user.value?.id) {
          await userApi.updatePreferences(user.value.id, preferences.value);
        }

        console.log("✅ 用户偏好设置更新成功");
      } catch (error) {
        console.error("❌ 更新用户偏好设置失败:", error);
        throw error;
      }
    };

    const changePassword = async (oldPassword: string, newPassword: string) => {
      try {
        if (!user.value?.id) throw new Error("用户未登录");

        await userApi.changePassword(user.value.id, oldPassword, newPassword);
        console.log("✅ 密码修改成功");
      } catch (error) {
        console.error("❌ 密码修改失败:", error);
        throw error;
      }
    };

    const updatePassword = async (passwordData: {
      oldPassword: string;
      newPassword: string;
    }) => {
      try {
        isLoading.value = true;
        const response = await userApi.updatePassword(passwordData);
        return response;
      } finally {
        isLoading.value = false;
      }
    };

    const updateEmail = async (emailData: { email: string; code: string }) => {
      try {
        isLoading.value = true;
        const response = await userApi.updateEmail(emailData);

        // 更新本地用户信息
        if (user.value) {
          user.value.email = emailData.email;
          user.value.emailVerified = true;
        }

        return response;
      } finally {
        isLoading.value = false;
      }
    };

    const updatePhone = async (phoneData: { phone: string; code: string }) => {
      try {
        isLoading.value = true;
        const response = await userApi.updatePhone(phoneData);

        // 更新本地用户信息
        if (user.value) {
          user.value.phone = phoneData.phone;
          user.value.phoneVerified = true;
        }

        return response;
      } finally {
        isLoading.value = false;
      }
    };

    const uploadAvatar = async (file: File) => {
      try {
        isLoading.value = true;
        const formData = new FormData();
        formData.append("file", file);

        const response = await userApi.uploadAvatar(formData);

        // 更新本地用户头像
        if (user.value) {
          user.value.avatar = response.data.url;
        }

        return response;
      } finally {
        isLoading.value = false;
      }
    };

    const deleteAccount = async () => {
      try {
        isLoading.value = true;
        const response = await userApi.deleteAccount();

        // 删除成功后清除所有本地数据
        await logout();

        return response;
      } catch (error) {
        throw error;
      } finally {
        isLoading.value = false;
      }
    };

    const getUserStats = async () => {
      if (!user.value?.id) throw new Error("用户未登录");
      const response = await userApi.getUserStats(user.value.id);
      return response.data;
    };

    const getUserPreferences = async () => {
      if (!user.value?.id) throw new Error("用户未登录");
      const response = await userApi.getUserPreferences(user.value.id);
      return response.data;
    };

    const verifyEmail = async (code: string) => {
      try {
        setLoading(true);
        const response = await userApi.verifyEmail({ code });

        if (user.value) {
          user.value.emailVerified = true;
          setUser(user.value);
        }

        return response;
      } finally {
        setLoading(false);
      }
    };

    const verifyPhone = async (code: string) => {
      try {
        setLoading(true);
        const response = await userApi.verifyPhone({ code });

        if (user.value) {
          user.value.phoneVerified = true;
          setUser(user.value);
        }

        return response;
      } catch (error) {
        throw error;
      } finally {
        setLoading(false);
      }
    };

    const sendVerificationEmail = async () => {
      try {
        if (!user.value?.email) throw new Error("用户邮箱不存在");
        const response = await userApi.sendVerificationEmail();
        return response;
      } catch (error) {
        throw error;
      }
    };

    const sendVerificationSMS = async () => {
      if (!user.value?.phone) throw new Error("用户手机号不存在");
      const response = await userApi.sendVerificationSMS();
      return response;
    };

    const resetPassword = async (email: string) => {
      try {
        setLoading(true);
        const response = await userApi.resetPassword({ email });
        return response;
      } finally {
        setLoading(false);
      }
    };

    const confirmResetPassword = async (data: {
      token: string;
      password: string;
    }) => {
      try {
        setLoading(true);
        const response = await userApi.confirmResetPassword(data);
        return response;
      } finally {
        setLoading(false);
      }
    };

    // 初始化时检查认证状态
    const initAuth = async () => {
      try {
        await checkAuth();
      } catch (error) {
        // 初始化失败不抛出错误，只是清除状态
        // 用户未登录或令牌已过期
      }
    };

    const hasAnyPermission = (permissionList: string[]) => {
      return permissionList.some((permission) =>
        hasPermission.value(permission),
      );
    };

    const checkAuth = async () => {
      try {
        // 检查本地是否有 token
        const localToken = localStorage.getItem("token");
        const localRefreshToken = localStorage.getItem("refreshToken");

        if (!localToken) {
          throw new Error("没有访问令牌");
        }

        // 设置 token
        token.value = localToken;
        if (localRefreshToken) {
          refreshToken.value = localRefreshToken;
        }

        // 验证 token 并获取用户信息
        const response = await userApi.getCurrentUser();
        setUser(response);

        return response;
      } catch (error) {
        // 验证失败，清除本地存储
        clearTokens();
        user.value = null;
        throw error;
      }
    };

    // 初始化用户状态
    const initUser = async () => {
      try {
        // 从本地存储恢复状态
        const savedToken = localStorage.getItem("token");
        const savedRefreshToken = localStorage.getItem("refreshToken");
        const savedUser = localStorage.getItem("user");
        const savedPreferences = localStorage.getItem("preferences");

        if (savedToken && savedUser) {
          token.value = savedToken;
          refreshToken.value = savedRefreshToken || "";
          user.value = JSON.parse(savedUser);

          // 验证令牌有效性并获取最新信息
          try {
            await fetchProfile();
          } catch (error) {
            // 令牌可能已过期，尝试刷新
            if (savedRefreshToken) {
              await refreshAccessToken();
              await fetchProfile();
            } else {
              // 无法恢复，清除状态
              await logout();
            }
          }
        }

        // 恢复用户偏好设置
        if (savedPreferences) {
          preferences.value = {
            ...preferences.value,
            ...JSON.parse(savedPreferences),
          };
        }

        // ✅ 用户状态初始化完成
      } catch (error) {
        // ❌ 用户状态初始化失败
        await logout();
      }
    };

    return {
      // 状态
      user,
      profile,
      token,
      refreshToken,
      isLoading,
      lastLoginTime,
      loginAttempts,
      preferences,

      // 计算属性
      isAuthenticated,
      userProfile,
      hasPermission,
      hasRole,
      isEmailVerified,
      isPhoneVerified,
      canLogin,

      // 方法
      setUser,
      setTokens,
      clearTokens,
      setLoading,
      resetLoginAttempts,
      login,
      register,
      logout,
      refreshAccessToken,
      checkAuth,
      updateProfile,
      updatePassword,
      updateEmail,
      updatePhone,
      uploadAvatar,
      deleteAccount,
      getUserStats,
      getUserPreferences,
      loadUserPreferences,
      updatePreferences,
      initAuth,
      fetchProfile,
      changePassword,
      hasAnyPermission,
      initUser,
      verifyEmail,
      verifyPhone,
      sendVerificationEmail,
      sendVerificationSMS,
      resetPassword,
      confirmResetPassword,
    };
  },
  {
    persist: {
      key: "user-store",
      paths: ["user", "token", "refreshToken", "lastLoginTime"],
      storage: localStorage,
    },
  },
);
